import { useState, useEffect, useRef, useCallback } from 'react'
import { LeagueDetail, LeagueMatch, LeaguePlayerRanking } from '@/types/dota'
import { openDotaAPI } from '@/services/api'
import { cacheManager } from '@/services/cacheManager'
import { incrementalUpdater } from '@/services/incrementalUpdater'
import { useToast } from '@/components/ui/toast'
import { useErrorHandler } from '@/utils/errorHandler'

interface LoadingState {
  detail: boolean
  matches: boolean
  ranking: boolean
}

interface ErrorState {
  detail: string | null
  matches: string | null
  ranking: string | null
}

interface UseLeagueDataReturn {
  // 数据状态
  leagueDetail: LeagueDetail | null
  leagueMatches: LeagueMatch[]
  leagueRanking: LeaguePlayerRanking | null
  
  // 加载状态
  loading: LoadingState
  error: ErrorState
  
  // 进度状态
  rankingProgress: { current: number; total: number; message: string }
  
  // 控制函数
  loadLeagueDetail: () => Promise<void>
  loadLeagueMatches: (page?: number, pageSize?: number) => Promise<void>
  loadLeagueRanking: () => Promise<void>
  refreshData: () => Promise<void>
  clearCache: () => void
  
  // 增量更新控制
  enableAutoUpdate: (interval?: number) => (() => void)
  disableAutoUpdate: () => void
  checkForUpdates: () => Promise<void>
  
  // 状态查询
  hasAnyData: boolean
  isAnyLoading: boolean
  hasAnyError: boolean
  lastUpdateCheck: number | undefined
  
  // 新增：总比赛数和统计信息
  totalMatchCount: number | null
  leagueStats: { radiantWins: number; direWins: number; totalMatches: number } | null
  loadLeagueStats: () => Promise<void>
}

export function useLeagueData(leagueId: number): UseLeagueDataReturn {
  const { addToast } = useToast()
  const errorHandler = useErrorHandler()
  
  // 数据状态
  const [leagueDetail, setLeagueDetail] = useState<LeagueDetail | null>(null)
  const [leagueMatches, setLeagueMatches] = useState<LeagueMatch[]>([])
  const [leagueRanking, setLeagueRanking] = useState<LeaguePlayerRanking | null>(null)
  
  // 加载状态
  const [loading, setLoading] = useState<LoadingState>({
    detail: false,
    matches: false,
    ranking: false
  })
  
  // 错误状态
  const [error, setError] = useState<ErrorState>({
    detail: null,
    matches: null,
    ranking: null
  })
  
  // 进度状态
  const [rankingProgress, setRankingProgress] = useState({
    current: 0,
    total: 0,
    message: ''
  })
  
  // 防止重复请求的引用
  const loadingRefs = useRef({
    detail: false,
    matches: false,
    ranking: false
  })
  
  // 当前页面状态
  const [currentPage, setCurrentPage] = useState(0)
  const [hasMoreMatches, setHasMoreMatches] = useState(true)
  const [totalMatchCount, setTotalMatchCount] = useState<number | null>(null)
  
  // 联赛统计状态
  const [leagueStats, setLeagueStats] = useState<{ radiantWins: number; direWins: number; totalMatches: number } | null>(null)
  
  // 自动更新状态
  const [autoUpdateEnabled, setAutoUpdateEnabled] = useState(false)

  // 加载联赛详情
  const loadLeagueDetail = useCallback(async (): Promise<void> => {
    if (loadingRefs.current.detail) {
      console.log('联赛详情正在加载中，跳过重复请求')
      return
    }

    try {
      loadingRefs.current.detail = true
      setLoading(prev => ({ ...prev, detail: true }))
      setError(prev => ({ ...prev, detail: null }))
      
      const detail = await openDotaAPI.getLeagueDetail(leagueId)
      if (detail) {
        setLeagueDetail(detail)
        
        // 成功提示
        addToast({
          type: 'success',
          title: '联赛详情加载成功',
          description: `已加载联赛 ${detail.name} 的详细信息`,
          duration: 3000
        })
      } else {
        throw new Error('未找到联赛详情')
      }
      
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取联赛详情失败'
      setError(prev => ({ ...prev, detail: errorMessage }))
      console.error('League detail error:', err)
      
      // 错误提示
      addToast({
        type: 'error',
        title: '联赛详情加载失败',
        description: errorMessage,
        duration: 5000,
        action: {
          label: '重试',
          onClick: () => loadLeagueDetail()
        }
      })
    } finally {
      setLoading(prev => ({ ...prev, detail: false }))
      loadingRefs.current.detail = false
    }
  }, [leagueId, addToast])

  // 加载联赛比赛
  const loadLeagueMatches = useCallback(async (page: number = 0, pageSize: number = 50): Promise<void> => {
    if (loadingRefs.current.matches) {
      console.log('联赛比赛正在加载中，跳过重复请求')
      return
    }

    try {
      loadingRefs.current.matches = true
      setLoading(prev => ({ ...prev, matches: true }))
      setError(prev => ({ ...prev, matches: null }))
      
      const matches = await openDotaAPI.getLeagueMatches(leagueId, page, pageSize)
      
      // 对于分页显示，总是替换当前数据而不是累积
      setLeagueMatches(matches)
      setCurrentPage(page)
      
      // 首次加载时，设置缓存的比赛数量
      if (page === 0 && matches.length > 0) {
        // 获取当前比赛总数并缓存
        try {
          console.log('useLeagueData - 尝试获取比赛总数...')
          const detailUpdate = await incrementalUpdater.checkLeagueDetailUpdates(leagueId)
          console.log('useLeagueData - detailUpdate结果:', detailUpdate)
          
          if (detailUpdate.matchCount !== undefined && detailUpdate.matchCount > 0) {
            cacheManager.setCachedMatchCount(leagueId, detailUpdate.matchCount)
            setTotalMatchCount(detailUpdate.matchCount)
            console.log(`useLeagueData - 设置联赛 ${leagueId} 缓存比赛数量: ${detailUpdate.matchCount}`)
          } else {
            console.warn('useLeagueData - detailUpdate.matchCount 无效，使用备用方案')
            // 备用方案：如果API返回的总数无效，尝试估算
            // 如果当前页返回了完整的pageSize数量，说明可能还有更多数据
            const estimatedTotal = matches.length === pageSize ? matches.length * 10 : matches.length
            setTotalMatchCount(estimatedTotal)
            console.log(`useLeagueData - 使用估算总数: ${estimatedTotal}`)
          }
        } catch (error) {
          console.warn('useLeagueData - 获取比赛总数失败，使用备用方案:', error)
          // 如果API完全失败，使用基本估算
          const estimatedTotal = matches.length === pageSize ? matches.length * 5 : matches.length
          setTotalMatchCount(estimatedTotal)
          console.log(`useLeagueData - API失败，使用基本估算: ${estimatedTotal}`)
        }
      }
      
      setHasMoreMatches(matches.length === pageSize)
      
      // 成功提示
      addToast({
        type: 'success',
        title: '比赛数据加载成功',
        description: `已加载 ${matches.length} 场比赛`,
        duration: 3000
      })
      
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取联赛比赛失败'
      setError(prev => ({ ...prev, matches: errorMessage }))
      console.error('League matches error:', err)
      
      // 错误提示
      addToast({
        type: 'error',
        title: '比赛数据加载失败',
        description: errorMessage,
        duration: 5000,
        action: {
          label: '重试',
          onClick: () => loadLeagueMatches(page, pageSize)
        }
      })
    } finally {
      setLoading(prev => ({ ...prev, matches: false }))
      loadingRefs.current.matches = false
    }
  }, [leagueId, addToast])

  // 加载联赛排名
  const loadLeagueRanking = useCallback(async (): Promise<void> => {
    if (loadingRefs.current.ranking) {
      console.log('联赛排名正在加载中，跳过重复请求')
      return
    }

    try {
      loadingRefs.current.ranking = true
      setLoading(prev => ({ ...prev, ranking: true }))
      setError(prev => ({ ...prev, ranking: null }))
      setRankingProgress({ current: 0, total: 0, message: '开始加载排名数据...' })
      
      const ranking = await openDotaAPI.getLeaguePlayerRanking(
        leagueId,
        (current: number, total: number, message: string) => {
          setRankingProgress({ current, total, message })
        }
      )
      
      setLeagueRanking(ranking)
      setRankingProgress({ current: 100, total: 100, message: '排名数据加载完成' })
      
      // 成功提示
      addToast({
        type: 'success',
        title: '玩家排名加载成功',
        description: `已加载 ${ranking.total_players} 名玩家的排名数据`,
        duration: 3000
      })
      
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取联赛排名失败'
      setError(prev => ({ ...prev, ranking: errorMessage }))
      setRankingProgress({ current: 0, total: 0, message: '加载失败' })
      console.error('League ranking error:', err)
      
      // 错误提示
      addToast({
        type: 'error',
        title: '玩家排名加载失败',
        description: errorMessage,
        duration: 5000,
        action: {
          label: '重试',
          onClick: () => loadLeagueRanking()
        }
      })
    } finally {
      setLoading(prev => ({ ...prev, ranking: false }))
      loadingRefs.current.ranking = false
    }
  }, [leagueId, addToast])

  // 加载联赛统计信息
  const loadLeagueStats = useCallback(async (): Promise<void> => {
    try {
      console.log('开始加载联赛统计信息...')
      const stats = await openDotaAPI.getLeagueStats(leagueId)
      setLeagueStats(stats)
      console.log('联赛统计信息加载完成:', stats)
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取联赛统计失败'
      console.error('League stats error:', err)
      
      // 设置默认值
      setLeagueStats({
        radiantWins: 0,
        direWins: 0,
        totalMatches: 0
      })
    }
  }, [leagueId])

  // 刷新所有数据
  const refreshData = useCallback(async (): Promise<void> => {
    // 清除缓存
    cacheManager.clearLeagueCache(leagueId)
    
    // 清空当前数据
    setLeagueDetail(null)
    setLeagueMatches([])
    setLeagueRanking(null)
    
    // 重新加载数据
    await Promise.all([
      loadLeagueDetail(),
      loadLeagueMatches(),
      loadLeagueRanking()
    ])
  }, [leagueId, loadLeagueDetail, loadLeagueMatches, loadLeagueRanking])

  // 清除缓存
  const clearCache = useCallback((): void => {
    cacheManager.clearLeagueCache(leagueId)
    
    addToast({
      type: 'success',
      title: '缓存已清除',
      description: '联赛数据缓存已清除',
      duration: 3000
    })
  }, [leagueId, addToast])

  // 启用自动更新
  const enableAutoUpdate = useCallback((interval: number = 5 * 60 * 1000): (() => void) => {
    setAutoUpdateEnabled(true)
    incrementalUpdater.startAutoUpdate(leagueId, {
      checkInterval: interval
    })
    
    // 监听更新事件
    const handleUpdate = (event: CustomEvent) => {
      const { type, leagueId: eventLeagueId } = event.detail
      
      if (eventLeagueId !== leagueId) return
      
      console.log(`自动更新: ${type}`)
      
      switch (type) {
        case 'detail':
          loadLeagueDetail()
          addToast({
            type: 'info',
            title: '联赛详情已更新',
            description: '发现新的联赛信息',
            duration: 3000
          })
          break
        case 'matches':
          loadLeagueMatches(0, 50)
          addToast({
            type: 'info',
            title: '比赛数据已更新',
            description: '发现新的比赛数据',
            duration: 3000
          })
          break
      }
    }
    
    window.addEventListener('leagueDataUpdate', handleUpdate as EventListener)
    
    // 清理函数
    return () => {
      window.removeEventListener('leagueDataUpdate', handleUpdate as EventListener)
    }
  }, [leagueId, addToast, loadLeagueDetail, loadLeagueMatches])

  // 禁用自动更新
  const disableAutoUpdate = useCallback((): void => {
    setAutoUpdateEnabled(false)
    incrementalUpdater.stopAutoUpdate(leagueId)
  }, [leagueId])

  // 手动检查更新
  const checkForUpdates = useCallback(async (): Promise<void> => {
    try {
      // 手动检查联赛详情更新
      const detailUpdate = await incrementalUpdater.checkLeagueDetailUpdates(leagueId)
      
      // 更新缓存的比赛数量
      if (detailUpdate.matchCount !== undefined) {
        cacheManager.setCachedMatchCount(leagueId, detailUpdate.matchCount)
      }
      
      if (detailUpdate.hasUpdates) {
        await loadLeagueDetail()
        await loadLeagueMatches(0, 50)
        addToast({
          type: 'success',
          title: '发现联赛更新',
          description: `发现新比赛，当前总数: ${detailUpdate.matchCount}`,
          duration: 3000
        })
      } else {
        addToast({
          type: 'info',
          title: '数据已是最新',
          description: `当前比赛总数: ${detailUpdate.matchCount || 0}`,
          duration: 3000
        })
      }
    } catch (error) {
      console.error('检查更新失败:', error)
      addToast({
        type: 'error',
        title: '检查更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        duration: 5000
      })
    }
  }, [leagueId, loadLeagueDetail, loadLeagueMatches, addToast])

  // 监听自动更新事件
  useEffect(() => {
    const handleUpdateEvent = (event: CustomEvent) => {
      const { type, leagueId: eventLeagueId } = event.detail
      
      if (eventLeagueId !== leagueId) return
      
      console.log(`收到联赛 ${leagueId} 的 ${type} 更新事件`)
      
      // 根据更新类型重新加载对应数据
      switch (type) {
        case 'detail':
          loadLeagueDetail()
          break
        case 'matches':
          loadLeagueMatches(0, 50)
          break
        case 'ranking':
          // 排名数据通常不会频繁更新，可以选择性处理
          break
      }
    }

    // 添加事件监听器
    window.addEventListener('leagueDataUpdate', handleUpdateEvent as EventListener)
    
    // 清理函数
    return () => {
      window.removeEventListener('leagueDataUpdate', handleUpdateEvent as EventListener)
    }
  }, [leagueId])

  // 初始化时检查缓存
  useEffect(() => {
    const initializeData = () => {
      // 检查是否有缓存数据
      const cachedDetail = cacheManager.getLeagueDetail(leagueId)
      const cachedMatches = cacheManager.getLeagueMatches(leagueId)
      const cachedRanking = cacheManager.getLeagueRanking(leagueId)
      const cachedMatchCount = cacheManager.getCachedMatchCount(leagueId)
      
      if (cachedDetail) {
        setLeagueDetail(cachedDetail)
        console.log(`从缓存恢复联赛 ${leagueId} 详情`)
      }
      
      if (cachedMatches) {
        setLeagueMatches(cachedMatches) // 显示所有缓存的比赛数据
        setHasMoreMatches(false) // 缓存数据不需要更多加载
        console.log(`从缓存恢复联赛 ${leagueId} 比赛数据，共 ${cachedMatches.length} 场比赛`)
      }
      
      if (cachedRanking) {
        setLeagueRanking(cachedRanking)
        console.log(`从缓存恢复联赛 ${leagueId} 排名数据`)
      }
      
      if (cachedMatchCount !== null) {
        setTotalMatchCount(cachedMatchCount)
        console.log(`从缓存恢复联赛 ${leagueId} 总比赛数: ${cachedMatchCount}`)
      }
    }

    initializeData()
  }, [leagueId])

  // 组件卸载时清理自动更新
  useEffect(() => {
    return () => {
      if (autoUpdateEnabled) {
        incrementalUpdater.stopAutoUpdate(leagueId)
      }
    }
  }, [leagueId, autoUpdateEnabled])

  // 计算派生状态
  const hasAnyData = !!(leagueDetail || leagueMatches.length > 0 || leagueRanking)
  const isAnyLoading = loading.detail || loading.matches || loading.ranking
  const hasAnyError = !!(error.detail || error.matches || error.ranking)
  const lastUpdateCheck = incrementalUpdater.getLastCheckTime(leagueId)

  return {
    // 数据状态
    leagueDetail,
    leagueMatches,
    leagueRanking,
    
    // 加载状态
    loading,
    error,
    rankingProgress,
    
    // 控制函数
    loadLeagueDetail,
    loadLeagueMatches,
    loadLeagueRanking,
    loadLeagueStats,
    refreshData,
    clearCache,
    
    // 增量更新控制
    enableAutoUpdate,
    disableAutoUpdate,
    checkForUpdates,
    
    // 状态查询
    hasAnyData,
    isAnyLoading,
    hasAnyError,
    lastUpdateCheck,
    
    // 总比赛数和统计信息
    totalMatchCount,
    leagueStats
  }
}